<template>
    <!-- 评论详情页容器 -->
  <!-- 加载状态提示 -->
  <view class="loading-tip" v-if="!postData">
    正在加载帖子数据
  </view>
  <view class="comment-container" v-if="postData">
    <!-- 顶部用户信息 -->
    <view class="user-header">
      <image class="avatar" src="/static/sample1.jpg"
      @click="goToPage('/pages/person/personal-page/personal-page?userId='+postData.userId)"></image>
      <view class="user-info">
        <text class="username" @click="goToPage('/pages/person/personal-page/personal-page?userId='+postData.userId)">{{ postData.nickName }}</text>
        <text class="post-time">{{ formatTimestamp(postData.createdAt) }}</text>
      </view>
      <uni-icons class="more-icon" type="more-filled" @click="showActionSheet"></uni-icons>
      <uni-popup ref="popup" type="bottom" :mask-click="true">
        <view class="popup-content">
          <view v-if="postData.userId === userId" class="popup-item delete-item" @click="deletePost">删除帖子</view>
          <view v-else class="popup-item cancel-item" @click="report">举报帖子</view>
          <view class="popup-item cancel-item" @click=" popup.value.close() ">取消</view>
        </view>
      </uni-popup>
    </view>


    <!-- 图片集 -->
    <swiper class="image-swiper" :circular="true">
      <swiper-item v-for="item in postData.parsedImageUrls">
        <image mode="aspectFit" :src="item" style="width:100%;height:100%;"/>
      </swiper-item>
     
    </swiper>

    <!-- 内容 -->
    <view class="main-comment">
      <text class="post-title">{{ postData.title }}</text>
      <text class="comment-text">
        {{ postData.content }}
      </text>
    </view>

    <!-- 地点信息 -->
    <view class="location-view" @click="goToPage('/pages/location/location?latitude='+postData.ggplocation.location.lat+'&longitude='+postData.ggplocation.location.lng+'&name='+postData.ggplocation.title+'&address='+postData.ggplocation.address)">
      <text class="location-text">{{ postData.ggplocation.title }}</text>
      <uni-icons type="arrowright" size="20" color="#666"></uni-icons>
    </view>

    <!-- 评论列表 -->
    <view class="comment-list" v-if="comments">
      <text class="comment-count">共{{comments.length}}条评论</text>
      
      <!-- 评论列表 -->
      <view class="comment-item" v-for="comment in comments" :key="comment.id">
				
        <image class="comment-avatar" :src="comment.avatarUrl" alt="没有头像"
        @click="goToPage('/pages/person/personal-page/personal-page?userId='+comment.userId)"></image>
        <view class="comment-content">
          <text class="comment-user" @click="goToPage('/pages/person/personal-page/personal-page?userId='+postData.userId)">{{comment.nickName}}</text>
          <text class="comment-text">{{ comment.content }}</text>
          <view class="comment-footer">
            <text class="comment-time">{{formatTimestamp(comment.createdAt)}}</text>
            <text class="reply-count" @click="showReplyInput(comment)">回复</text>
          </view>
          
          <!-- 回复内容 -->
          <view class="reply-items" v-if="comment.replies">
            <view class="reply-item" v-if="comment.expanded"  
            v-for="(reply, index) in comment.replies">
              <text class="reply-user" @click="goToPage('/pages/person/personal-page/personal-page?userId='+reply.userId)">{{reply.nickName}}</text>
              <text class="reply-user" v-if="reply.toUserId" @click="goToPage('/pages/person/personal-page/personal-page?userId='+reply.toUserId)">回复 {{reply.toNickName}}</text>
							
              <text class="reply-text" @click="showReplyInput(reply)">{{reply.content}}</text>
            </view>
           <!-- <view class="reply-item" v-for="(reply, index) in comment.replies" 
                  :key="reply.user" v-else>
              <text class="reply-user" @click="goToPage('/pages/person/personal-page/personal-page?userId='+postData.userId)">{{reply.user}}</text>
              <text class="reply-text">{{reply.text}}</text>
            </view> -->
          </view>
					
					<text class="more-replies"
					      v-if="comment.replyCount >= 1"
					      :class="{collapsed: comment.expanded}"
					      @click="toggleReply(comment)">
					  {{comment.expanded ? '收起' : `展开${comment.replyCount}条回复`}}
					</text>
        </view>
      </view>
    </view>

    <!-- 底部操作栏 -->
    <view style="height: 200rpx;"></view>
    <view class="action-bar">
      <view class="input-box">
        <input 
          v-model="replyText" 
          :focus="isReplying" 
          placeholder="说点什么..." 
          confirm-type="发送"
          @confirm="submitReply"
        />
      </view>
      <view class="action-icons">
        <view class="icon-item" @click="toggleLike">
          <!-- #ifdef MP-WEIXIN -->
          <uni-icons class="icon" :type="isLiked ? 'heart-filled' : 'heart'" :color="isLiked ? '#ff2442' : '#333333'"></uni-icons>
          <!-- #endif -->
          <!-- #ifndef MP-WEIXIN -->
          <uni-icons class="icon" :type="isLiked ? 'heart-filled' : 'heart'" :style="{ color: isLiked ? '#ff2442' : '' }"></uni-icons>
          <!-- #endif -->
          <text class="count">{{likeCount}}</text>
        </view>
        <view class="icon-item" @click="toggleStar">
          <!-- #ifdef MP-WEIXIN -->
          <uni-icons class="icon" :type="isStarred ? 'star-filled' : 'star'" :color="isStarred ? '#ffcc00' : '#333333'"></uni-icons>
          <!-- #endif -->
          <!-- #ifndef MP-WEIXIN -->
          <uni-icons class="icon" :type="isStarred ? 'star-filled' : 'star'" :style="{ color: isStarred ? '#ffcc00' : '' }"></uni-icons>
          <!-- #endif -->
          <text class="count">{{starCount}}</text>
        </view>
        <view class="icon-item" @click="toggleShare">
          <uni-icons class="icon" type="paperplane"></uni-icons>
          <text class="count">{{shareCount}}</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import { onLoad } from '@dcloudio/uni-app'
import { http } from '@/utils/request'
import { formatTimestamp } from '../../../utils/dateUtils'

const postData = ref(null)
const comments = ref([])
const postId = ref('')
const userId =ref('')

const isLiked = ref(false)
const isStarred = ref(false)
const likeCount = ref(0)
const starCount = ref(0)
const shareCount = ref(0)

onLoad((options) => {
  const images = ['/static/sample1.jpg', '/static/sample2.jpg']
  postId.value = options.postId; // 获取参数
  console.log('接收到的postId:', postId.value);

  fetchPostData();
  Promise.all(images.map(img => {
    return new Promise((resolve) => {
      uni.getImageInfo({
        src: img,
        success: (res) => {
          const ratio = res.height / res.width
          resolve(ratio)
        },
        fail: () => resolve(1) // 默认1:1
      })
    })
  })).then(ratios => {
    imageRatios.value = ratios
    const minRatio = Math.min(...ratios)
    swiperHeight.value = `calc(100vw * ${minRatio})`
  })
})

// 获取帖子数据
const fetchPostData = async () => {
  try {
	  // console.log("开始获取数据");
	  userId.value = uni.getStorageSync('userId')
	  const result = await http.get(`/posts/by-id/check?postId=${postId.value}&userId=${userId.value}`)
	  const res = result.data
	  console.log("获取数据完成：",res);
    if (res) {
      // 映射数据到对应字段
      isLiked.value = res.isLike === 1
      likeCount.value = res.post.likeCount
      isStarred.value = res.isFavorite === 1
      starCount.value = res.post.favoriteCount
      postData.value = res.post
      comments.value.push(...res.comments)
      console.log("postData.value:",postData.value);
      uni.setNavigationBarTitle({
				title:postData.value.nickName+' 的帖子'
			})
    }
		
    // else console.log("没有数据");
  } catch (error) {
    console.error('获取帖子数据失败:', error)
    uni.showToast({
      title: '数据加载失败',
      icon: 'error'
    })
  }
}


const toggleLike = async () => {
	if(!userId.value){
		uni.showToast({
		  title: '请先登录',
		  icon: 'error'
		})
		return;
	}
  try {
    const originalLiked = isLiked.value
    const originalCount = likeCount.value
    
    // 先更新UI状态
    isLiked.value = !originalLiked
    likeCount.value += isLiked.value ? 1 : -1
    
    // 调用后端API
    if (isLiked.value) {
      await http.post(`/likes/${postId.value}`)
    } else {
      await http.delete(`/likes/${postId.value}`)
    }
  } catch (error) {
    // 如果API调用失败，回滚UI状态
    isLiked.value = originalLiked
    likeCount.value = originalCount
    uni.showToast({
      title: '操作失败，请重试',
      icon: 'error'
    })
    console.error('点赞操作失败:', error)
  }
}

const toggleStar = async () => {
	if(!userId.value){
			uni.showToast({
			  title: '请先登录',
			  icon: 'error'
			})
			return;
		}
	try {
	  const originalStar = isStarred.value
	  const originalCount = starCount.value
	  
	  // 先更新UI状态
	  isStarred.value = !originalStar
	  starCount.value += isStarred.value ? 1 : -1
	  
	  // 调用后端API
	  if (isStarred.value) {
	    await http.post(`/favorites/${postId.value}`)
	  } else {
	    await http.delete(`/favorites/${postId.value}`)
	  }
	} catch (error) {
	  // 如果API调用失败，回滚UI状态
	  isLiked.value = originalStar
	  starCount.value = originalCount
	  uni.showToast({
	    title: '操作失败，请重试',
	    icon: 'error'
	  })
	  console.error('收藏操作失败:', error)
	}
	if(!userId.value){
		uni.showToast({
		  title: '请先登录',
		  icon: 'error'
		})
		return;
	}
}

const toggleShare = () => {
  // 分享功能可以在这里实现
  uni.showToast({
    title: '分享成功',
    icon: 'success'
  })
  shareCount.value += 1
}

const swiperHeight = ref('100vw') // 默认1:1
const imageRatios = ref([])

const goToPage = (url) => {
  if (!url) return
  uni.navigateTo({
    url
  })
}


// 评论
const toggleReply = async (comment) => {
  comment.expanded = !comment.expanded
	const res = await http.get('/api/replies/comment',{
		commentId : comment.commentId
	})
	comment.replies = res.data.records
	console.log(comment.replies);
}

const currentReplyComment = ref(null)
const replyText = ref('')
const isReplying = ref(false)

const showReplyInput = (comment) => {
	console.log(comment);
	console.log('replyId' in comment);
  currentReplyComment.value = comment
  replyText.value = ''
  isReplying.value = true
}
const popup =ref()
const showActionSheet = () => {
	popup.value.open('bottom')
}
const deletePost = async () => {
  try {
    const res = await http.delete(`/posts`,{
			postIds : postId.value
		})
		console.log(res);
		uni.navigateBack()
    uni.showToast({
      title: '删除成功',
      icon: 'success'
    })
  } catch (error) {
    uni.showToast({
      title: '删除失败',
      icon: 'error'
    })
    console.error('删除帖子失败:', error)
  } finally {
    popup.value.close()
  }
}

const report = () => {
	uni.showToast({
		title: '已收到你的举报'
	})
	popup.value.close()
}

const submitReply = async () => {
  if (!replyText.value.trim()) return
  if(!userId.value){
		uni.showToast({
			title: '请先登录',
			icon: 'error'
		})
		return;
	}
	
  try {
		if(isReplying.value){
			if('replyId' in currentReplyComment.value){
				const res = await http.post(`/api/replies`,{
					commentId : currentReplyComment.value.commentId,
					content: replyText.value.trim(),
					toUserId : currentReplyComment.value.userId
				})
				// console.log(res.data);
				const index = comments.value.findIndex(item=>item.commentId === res.data.commentId)
				console.log("comment:",comments.value[index].replies);
				comments.value[index].replies.unshift(res.data)
			}else{
				const res = await http.post(`/api/replies`,{
					commentId : currentReplyComment.value.commentId,
					content: replyText.value.trim()
				})
				console.log(res.data);
				const index = comments.value.findIndex(item=>item.commentId === res.data.commentId)
				if(comments.value[index].replies){
					console.log("has reply");
					comments.value[index].replies.unshift(res.data)
				}else{	
					console.log("no reply");
					comments.value[index].replies = [res.data]
					comments.value[index].expanded = true
				}
				console.log("comment:",comments.value[index].replies);
				
			}
		}else{
			const res = await http.post(`/api/comment/create`,{
				postId: postId.value,
				content: replyText.value.trim()
			})
			const newComment = res.data;
			comments.value.unshift(newComment)
		}
  } catch (error) {
    uni.showToast({
      title: '操作失败，请重试',
      icon: 'error'
    })
    console.error('评论操作失败:', error)
  } finally {
		// 重置状态
		replyText.value = ''
		isReplying.value = false
		currentReplyComment.value = null
	}
  
  
}


</script>

<style>
.comment-container {
  background: #ffffff;
  padding: 20rpx;
}

/* 顶部用户信息 */
.user-header {
  display: flex;
  align-items: center;
  margin-bottom: 30rpx;
}

.avatar {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  margin-right: 20rpx;
}

.user-info {
  flex: 1;
}

.username {
  font-size: 32rpx;
  font-weight: bold;
  display: block;
}

.post-time {
  color: #888;
  font-size: 24rpx;
}

.follow-btn {
  padding: 8rpx 24rpx;
  border: 1rpx solid #ddd;
  border-radius: 40rpx;
  color: #666;
}

/* 主评论内容 */
.main-comment {
  margin: 40rpx 10rpx;
}
.post-title{
  font-size: 20px;
  font-weight: bold;
  color: #333;
  margin: 20rpx 10rpx;
  display: block;
}
.comment-text {
  font-size: 30rpx;
  line-height: 1.5;
  white-space: pre-wrap;
}

.hashtag {
  color: #007AFF;
  /* margin-left: 10rpx; */
}

.image-indicator {
  background: rgba(0,0,0,0.6);
  color: white;
  padding: 8rpx 16rpx;
  border-radius: 32rpx;
  position: absolute;
  right: 30rpx;
  bottom: 30rpx;
}

/* 地点信息 */
.location-view {
  background: #f5f5f5;
  border-radius: 12rpx;
  padding: 20rpx;
  margin: 20rpx 0;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.location-text {
  font-size: 28rpx;
  color: #333;
}

/* 评论列表 */
.comment-list {
  border-top: 1rpx solid #eee;
  padding-top: 30rpx;
}

.comment-count {
  color: #888;
  font-size: 28rpx;
  margin-bottom: 30rpx;
}

.comment-item {
  display: flex;
  margin: 40rpx 0;
}

.comment-avatar {
  width: 64rpx;
  height: 64rpx;
  border-radius: 50%;
  margin-right: 20rpx;
}

.comment-content {
  flex: 1;
}

.comment-user {
  color: #666;
  font-size: 28rpx;
  margin-right: 20rpx;
  margin-bottom: 20rpx;
  display: block;
}

.highlight {
  color: #FF2442;
  font-weight: bold;
}

.comment-footer {
  display: flex;
  align-items: center;
  margin-top: 16rpx;
}

.comment-time {
  color: #888;
  font-size: 24rpx;
}

.reply-count {
  color: #3e9cff;
  font-size: 24rpx;
  margin-left: 20rpx;
}

/* 回复内容 */
.reply-items {
  background: #f8f8f8;
  border-radius: 12rpx;
  padding: 20rpx;
  margin: 20rpx;
  margin-left: 0;
  font-size: 25rpx;
}
.reply-item {
  margin-bottom: 5px;
}
.reply-user {
  color: #4d4d4d;
  margin-right: 16rpx;
}
.reply-text {
  color: #8d8d8d;
  margin-right: 16rpx;
}

.reply-user {
  color: #4d4d4d;
  margin-right: 16rpx;
}

.more-replies {
  display: block;
  color: #3e9cff;
  font-size: 24rpx;
  margin-top: 16rpx;
}
.more-replies.collapsed {
  color: #888;
}

/* 底部操作栏 */
.action-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: white;
  padding: 20rpx;
  display: flex;
  align-items: center;
  box-shadow: 0 -4rpx 12rpx rgba(0,0,0,0.05);
}

.input-box {
  flex: 1;
  background: #f5f5f5;
  border-radius: 48rpx;
  padding: 10rpx 20rpx;
  margin-right: 30rpx;
}

.input-box input {
  width: 100%;
  height: 60rpx;
  font-size: 28rpx;
  padding: 0 10rpx;
}

.action-icons {
  display: flex;
  align-items: center;
}

.icon-item {
  margin-left: 40rpx;
  text-align: center;
}

.icon {
  font-size: 44rpx;
  display: block;
  margin-bottom: 8rpx;
  transition: all 0.3s;
}

.icon-item:active .icon {
  transform: scale(1.2);
  animation: bounce 0.5s;
}

@keyframes bounce {
  0%, 100% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.3);
  }
}

.count {
  font-size: 24rpx;
  color: #666;
}

.more-icon {
  margin-left: auto;
  padding: 0 20rpx;
  font-size: 40rpx;
  color: #666;
}

.popup-content {
  background-color: #fff;
	width: 100%;
	box-sizing: border-box;
  border-radius: 24rpx 24rpx 0 0;
  padding: 30rpx;
	position: fixed;
	bottom: 0;
}

.popup-item {
  padding: 30rpx 0;
  text-align: center;
  font-size: 32rpx;
  border-bottom: 1rpx solid #eee;
}

.popup-item:last-child {
  border-bottom: none;
}

.delete-item {
  color: #ff2442;
}

.cancel-item {
  color: #333;
}
</style>
